import { Layout, Menu } from 'antd'
import * as Icon from '@ant-design/icons'
import React from 'react'
import MenuConfig from './../../config/index.js'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { selectMenuList } from '../../store/reducers/tab.js'

const { Sider } = Layout

const iconToElement = (name) => React.createElement(Icon[name])

// 处理菜单数据
const pathList = MenuConfig.map((pathItem) => {
  // 没有子菜单
  const child = {
    key: pathItem.path,
    icon: iconToElement(pathItem.icon),
    label: pathItem.label
  }
  // 有子菜单
  if (pathItem.children) {
    child.children = pathItem.children.map((childItem) => ({
      key: childItem.path,
      icon: iconToElement(childItem.icon),
      label: childItem.label
    }))
  }
  return child
})

function Aside({ collapse }) {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  // 添加数据到store中
  const setTabsList = (val) => {
    dispatch(selectMenuList(val))
  }
  const selectMenu = (e) => {
    let data = ''
    MenuConfig.forEach((item) => {
      if (item.path === e.key) {
        data = item
      }
      // 如果有二级
      if (item.children?.length > 1) {
        item.children.forEach((child) => {
          if (child.path === e.key) {
            data = child
          }
        })
      }
    })
    setTabsList({
      path: data.path,
      label: data.label,
      name: data.name
    })
    console.log(data)
    navigate(e.key)
  }
  return (
    <Sider trigger={null} collapsible collapsed={collapse}>
      <p class='sys-title'>{collapse ? '后台' : 'react后台通用系统'}</p>
      <Menu
        theme='dark'
        mode='inline'
        defaultSelectedKeys={['1']}
        items={pathList}
        onClick={selectMenu}
      />
    </Sider>
  )
}

export default Aside
